import axios from 'axios'
import { Message } from 'element-ui'
import Nprogress from 'nprogress'
import { getUserInfo, removeUserInfo } from '@/utils/auth'
import router from '@/router'

const request = axios.create({
  baseURL: '/api',
  timeout: 5000
})

request.interceptors.request.use(config => {
  Nprogress.start()
  const userInfo = getUserInfo()
  if (userInfo) {
    config.headers.token = userInfo.token
  }
  return config
}, error => {
  return Promise.reject(error)
})

request.interceptors.response.use(response => {
  Nprogress.done()
  if (response.data.code !== 1) {
    return Promise.reject(new Error(response.data.msg))
  }
  return response.data
}, error => {
  Nprogress.done()
  if (error.response && error.response.status === 401) {
    removeUserInfo()
    router.push('/login')
    Message.error('请重新登录')
  }
  return Promise.reject(error)
})

export default request
